<template>
  <div class="app-container">
    <div style="font-weight: 700;padding-bottom: 20px;">
    </div>
    <!-- <Progress :newStep="param.newStep" /> -->
    <!-- {{rowData}} -->
    <el-row :gutter="10">
      <el-col :span="18">
        <el-card>
          <el-row style="height: 360px;">
            <el-col :span="8">
              <span style="font-size: 16px;font-weight: 600;">{{ rowData.companyName }}</span>
              <div style="margin-top: 10px;position: relative;">
                <Carousel v-bind="swiperData" style="position: absolute;top: 10px;"></Carousel>
              </div>
            </el-col>
            <el-col :offset="1" :span="12">
              <div style="font-size: 14px;text-align: left; box-sizing: border-box;padding: 20px;">
                <el-row :gutter="10">
                  <el-col :span="10">
                    <span style="font-weight: bolder;font-size: 20px;">{{ rowData.carryCityName }}</span>
                    <div class="marginTop10" style="margin-top: 10px;color: #aaa;">
                      提箱城市：{{ rowData.carryCityName }}/{{ rowData.carryCountryName }}
                    </div>
                  </el-col>
                  <el-col :span="4"><img style="text-align: center; width: 17px;"
                      src="@/assets/icons/svg/right.svg"></el-col>
                  <el-col :span="10" style="text-align: right;">
                    <span style="font-weight: 800;font-size: 20px;">{{ rowData.returnCityName }}</span>
                    <div class="marginTop10" style="margin-top: 10px;color: #aaa;">
                      还箱城市：{{ rowData.returnCityName }}/{{ rowData.returnCountryName }}
                    </div>
                  </el-col>
                </el-row>

                <el-row class="marginTop50">
                  <el-col :span="5">租赁单价</el-col>
                  <el-col :span="12" style="color: #ff0000;font-weight: 600;">{{param.unitCurrency}}{{ param.unitPrice }}</el-col>
                </el-row>
                <el-row class="marginTop20">
                  <el-col :span="5">箱使期</el-col>
                  <el-col :span="12"> {{ rowData.boxUsagePeriod }} 天</el-col>
                </el-row>
                <el-row class="marginTop20">
                  <el-col :span="5">箱型</el-col>
                  <el-col :span="12"> {{ boxTypeFilter(param.boxType) }}</el-col>
                </el-row>
                <el-row class="marginTop20">
                  <el-col :span="5">箱况</el-col>
                  <el-col :span="12"> {{ boxConditionFilter(param.boxCondition) }}</el-col>
                </el-row>
                <el-row class="marginTop20">
                  <el-col :span="5">租箱量</el-col>
                  <el-col :span="12"> 
                    <el-input-number v-model="param.num" :min="0" :max="9999" @change="handleChange" />
                  </el-col>
                </el-row>
              </div>
            </el-col>
          </el-row>
          <!-- <orderInfoForm :showInvoiceType="false" ref="infoFormRef" :type="'tx'"></orderInfoForm> -->

        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card style="height: 100%;position:relative">
          <el-row class="marginTop20">
            <el-col :span="12">租箱金额</el-col>
            <!-- <el-col :span="6">{{ boxTypeFilter(param.boxType) }} * {{ param.num }}</el-col> -->
            <el-col :span="12" style="text-align: right;color: #eb2a2a;">{{param.unitCurrency}} {{ numMulti(param.unitPrice, param.num) }}</el-col>
          </el-row>  
          <el-row class="marginTop20">
            <el-col :span="12">优惠券</el-col>
            <el-col :span="12">
              <el-select style="width:100%" v-model="param.coupon">
                  <el-option label="无优惠券" value="" />
                  <el-option label="100优惠券" value="100"/>
                  <el-option label="100优惠券" value="1000"/>
                </el-select>
            </el-col>
          </el-row>  
          <el-row class="marginTop10" style="border-top: #999999 1px dashed;position:absolute;bottom:20px;width: 88%;">
            <el-col :span="24">
                  <el-row class="marginTop10">
                    <el-col :span="12">合计</el-col>
                    <el-col :span="12" style="text-align: right; color: #eb2a2a;">{{param.unitCurrency}} {{ numMulti(param.unitPrice, param.num) }}</el-col>
                  </el-row>
              </el-col>
          </el-row> 
        </el-card>
      </el-col>
    </el-row>
    <!-- <el-col :span="24">
        <el-card class="pag-container">
          <el-row class="marginTop20">
            <el-col :span="3"></el-col>
            <el-col :span="3">租箱金额</el-col>
            <el-col :span="6">{{ boxTypeFilter(param.boxType) }} * {{ param.num }}</el-col>
            <el-col :span="4" style="text-align: right;color: #2020eb;">{{param.unitCurrency}} {{ numMulti(param.unitPrice, param.num) }}</el-col>
          </el-row>  
          <el-row class="marginTop20">
            <el-col :span="3"></el-col>
            <el-col :span="3">优惠券</el-col>
            <el-col :span="5"></el-col>
            <el-col :span="5">
              <el-select style="width:100%" v-model="param.coupon">
                  <el-option label="无优惠券" value="" />
                  <el-option label="100优惠券" value="100"/>
                  <el-option label="100优惠券" value="1000"/>
                </el-select>
            </el-col>
          </el-row>  
          <div style="border: 1px solid #f1f1f1; margin-top: 10px;"></div>
          <el-row class="marginTop20">
            <el-col :span="16" style="text-align: right; color: #2020eb;">{{param.unitCurrency}} {{ numMulti(param.unitPrice, param.num) }}</el-col>
          </el-row> 
        </el-card>
      </el-col> -->

    <el-card class="pag-container">
      <span style="font-weight: 700;font-size: 15px;">
        <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span>订单信息
      </span>
      <orderInfoForm :showInvoiceType="false" ref="infoFormRef" :type="'tx'"></orderInfoForm>
    </el-card>

    <el-card class="pag-container">
      <orderAllocation ref="allocationRef" :handledBy="true"  :rowData="rowData" :userSimpleList="param.userSimpleList"></orderAllocation>
    </el-card>
    <el-row style="width:100%;text-align: center;margin-top: 30px;">
      <div style="width:100%;text-align: center;">
        <div>
          <el-checkbox v-model="param.radioVal" size="large" />
          我已阅读<a style="color: #2020eb;" href="#">《集装箱租赁业务规则》</a>
                <a style="color: #2020eb;" href="#">《用户服务协议和管理规则》</a>并同意全部条款
          </div>
        <el-button @click="handleSubmit" type="primary">提交订单</el-button>
      </div>
    </el-row>
  </div>
</template>
<script lang="ts" setup>
import { numMulti } from '@/utils/compute';
import  Carousel from '@/components/carousel'
import { computed, onMounted, reactive, ref, watch ,onActivated} from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { agentAddOrder } from '@/api/orderManage'
import orderInfoForm from '@/views/components/order/orderInfoForm.vue'
import orderAllocation from '@/views/components/order/orderAllocation.vue'
import orderInfo from '@/store/modules/order'
import { ElMessage } from 'element-plus';
import { getBoxInfo } from '@/api/boxRent'
const $route = useRoute();
const router = useRouter()

const props = defineProps({
  data: {
    type: Object,
    default: () => {
      return {}
    }
  }
})

const param = reactive({
  dialogVisible: false,
  boxConditionList: [],
  boxTypeList: [],
  boxType: '',
  boxCondition: '',
  num: 0,
  page: 1,
  limit: 10,
  coupon:"",
  newStep: 1,
  planPickupDate: new Date(),
  paymentMethod: '5',
  handleUser: 4,

  //订单分配 
  handleUserList: [{ "handleUserId": 4, "handleUserName": "李四" }],
  // operateUsers: [],
  operateUserList: [{ "operateUserId": 3, "operateUserName": "张三" }, { "operateUserId": 5, "operateUserName": "王五" }],
  // businessUser: '',
  businessUserList: [{ "businessUserId": 4, "businessUserName": "李四" }, { "businessUserId": 6, "businessUserName": "赵六" }],
  // businessNo: '',
  allocation: [{ 'operateUsers': [3, 5], "businessUser": 4, "businessNo": "NO1234567890" }],
  // form0: { 'operateUsers': [3, 5], "businessUser": 2, "businessNo": "NO1234567890" },
  radioVal:false
})

const inventory = computed(() => {
  let tagDataList = rowData.value.releaseRentPriceList
  let num = 0
  if (!tagDataList) return 0
  tagDataList.forEach((item: any) => {
    if (item.boxType == param.boxType && item.boxCondition == param.boxCondition) {
      num = item.inventory
    }
  })
  return num
})
const swiperData = reactive({
  list: [],
  config: {
    width:"100%",
    height:"330px"
  }
})

// watch(() => orderInfo().rowData, async () => {
//   getSetBoxInfo()
// })
// onMounted(() => {
//   getSetBoxInfo()

// })
onActivated(() => {
  getSetBoxInfo()
})

// 获取数据
const mainFileList = ref([])
// const detailFileList = ref([])
const rowData = ref({})
import { userSimpleList } from '@/api/user/index' 

const getSetBoxInfo = async () => {
  let row = orderInfo().rowData
  if(row){ //详情跳转
    let result=row
    rowData.value = result
    param.newStep = result.status
    mainFileList.value = JSON.parse(result.mainFileList)
    swiperData.list = JSON.parse(result.mainFileList)
    if(row?.submitData){//详情
      setBoxInfo(row?.submitData)

    }else{//列表
      getSetBoxInfoDetai()
    }
    userListTes()
  }
}
//详情接口
const getSetBoxInfoDetai = async () => {
  const row = orderInfo().rowData
  if (row) {
    await getBoxInfo(row.releaseRentId).then((res: any) => {
      const result = res.data
      mainFileList.value = JSON.parse(result.mainFileList)
      swiperData.list = JSON.parse(result.mainFileList)
      param.newStep = result.status
      if(result.releaseRentPriceList){
        let dataInfo=result.releaseRentPriceList[0]
        param.boxType = dataInfo.boxType
        param.boxCondition = dataInfo.boxCondition
        param.unitCurrency = dataInfo.currency=='USD' ? "$":'¥'
        param.unitPrice = dataInfo.unitPrice
        param.inventory = dataInfo.inventory
      }
      param.num = 0
      rowData.value = result
    })
  }
}


//列表跳转获取数据
const userListTes = async()=>{
  await userSimpleList({}).then(res => {
    let userList = []
    res.data.forEach((item:any) => {
      let obj = {"userId":item.userId,"userName":item.nickname}
      userList.push(obj)
    })
    
    param.userSimpleList = userList
  })
}
//提交订单
const handleSubmit = async () => {
  if(!param.radioVal) return ElMessage.warning('请先阅读《集装箱租赁业务规则》、《用户服务协议和管理规则》并同意全部条款')
  const infoFormValidate = await infoFormRef.value.onSubmit() // validate
  const allocationValidate = await allocationRef.value.onSubmit()
  if (!infoFormValidate || !allocationValidate) {
    ElMessage.warning('订单信息 校验未通过')
    return
  }
  handleSign()
}
// 
const infoFormRef = ref({ formData: {}, onSubmit: () => { } })
const allocationRef = ref({ allocation: [], onSubmit: () => { } })
const handleSign = async () => {
  console.log('handleSign')
  const allocation = allocationRef.value.getAllocationTemplate()
  const formData = infoFormRef.value.formData
  const data = {
    "releaseRentId": rowData.value.id,
    "boxType": param.boxType,
    "boxCondition": param.boxCondition,
    "boxQuantity": param.num,
    "planPickupDate": formData.planPickupDate,
    "paymentMethod": formData.paymentMethod - 0,
    "invoiceType": formData.invoiceType - 0,
    "contacts": formData.contacts,
    "tel": formData.tel,
    "period":formData.period,
    "areaCode": formData.areaCode,
    "leaveMsg": formData.leaveMsg,
    "allocation": JSON.stringify(allocation)
    //allocation:[{ operateUsers: [{ "operateUserId": 1, "operateUserName": "操作员" }], "businessUserId": 2, "businessUserName": "业务员", "businessNo": "NO1234567890" }]
  }
  console.log("datadatadata",data)
  // return
  agentAddOrder(data).then((res: any) => {
    router.push('rentBox')
    ElMessage.success('下单成功')
  })
}

// 
const setBoxInfo = (data: any) => {
  param.boxType = data.boxType
  param.boxCondition = data.boxCondition
  param.num = data.num
  param.unitPrice = data.unitPrice
  param.inventory = data.inventory,
  param.unitCurrency = data.unitCurrency
}

//
const handleChange = (value: Number) => {
  console.log(value)
  if (!inventory) {

  }
}

//过滤
const boxTypeFilter = (val: any) => {
  let result = ''
  const boxConditionList = [{ value: 5, label: '40HQ' }, { value: 10, label: '40GP' }, { value: 15, label: '20HQ' }, { value: 20, label: '20GP' }]
  boxConditionList.forEach((item: { value: any; label: any; }) => {
    if (item.value == val) {
      result = item.label
    }
  })
  return result
}
const boxConditionFilter = (val: any) => {
  let result = ''
  const boxTypeList = [{ value: 15, label: '适货' }, { value: 10, label: '次新' }, { value: 20, label: '混提' },{ value: 5, label: '全新' }]
  boxTypeList.forEach((item: { value: any; label: any; }) => {
    if (item.value == val) {
      result = item.label
    }
  })
  return result
}
// const operateUserNameFilter = (val: any) => {
//   let result = ''
//   param.operateUserList.map((item: { operateUserId: any; }) => {
//     if (item.operateUserId == val) {
//       result = item.operateUserName
//     }
//   })
//   return result
// }

// const getAllocationTemplate = () => {
//   let arry = []
//   const handleUser = param.handleUserList.find((item: any) => {
//     return item.handleUserId == param.handleUser
//   })
//   param.allocation.forEach((el, index) => {
//     const operateUsers: any = []
//     el.operateUsers.map((id: any) => {
//       operateUsers.push({ "operateUserId": id, "operateUserName": operateUserNameFilter(id) })
//     })
//     const businessUser = param.businessUserList.find((item: any) => {
//       return item.businessUserId == el.businessUser
//     })
//     arry.push({ "handleUserId": handleUser.handleUserId, "handleUserName": handleUser.handleUserName, "operateUsers": operateUsers, "businessUserId": el.businessUser, "businessUserName": businessUser.businessUserName, "businessNo": el.businessNo })
//   })
//   return arry
// }

</script>
<style lang="scss" scoped>
.pag-container {
  margin-top: 20px;
  box-sizing: border-box;
  padding: 10px;
}
</style>